#!/usr/bin/env python
# encoding: utf-8
'''
Created on Jun 6, 2011

@author: apple
'''

from flask import Module, render_template, request, jsonify , flash , session, redirect, url_for
from questionmodel import setquestion, getquestion, searchquestion , getnewestquestions 
import questionmodel as model
from apps.user.usermodel import getuser
from application import cache,app

question = Module(__name__ , name='question')

@question.route('/q')
def ask():
    if not '_id' in session:
        return redirect(url_for('user.login'))
    _,catalogs = app.signal_gettopcatalog.send(__name__)[0]
    return render_template('question/ask.html',cs = catalogs)

@question.route('/summit', methods=['POST', 'GET'])
def summit():
    title = request.form.get('title', '')
    summary = request.form.get('summary', '')
    tags  = [t.lower() for t in request.form.get('tags','').split()]
    _id = setquestion({'uid':'alan.yang@live.com' , 'title':title , 'summary':summary,'tags':tags})
    return render_template('question/answer.html', _id=_id)

@question.route('/d/<qid>')
def detail(qid, errorcode=0):
    if errorcode:
        return render_template('question/detail.html')
    question = getquestion(qid)
    uid = session.get('uid', None)
    user = getuser(uid) if uid else None
    return render_template('question/detail.html' , question=question , user=user)


@question.route('/s')
def search():
    kw = request.args.get('q', None)
    if not kw:
        return render_template('question/search.html')
    questions = searchquestion(kw)
    return '<br />'.join(['<h3>%s</h3><br>' % (q['data']['title']) for q in questions])
    
@question.route('/')
#@cache.cached(timeout=120)
def index():
    qs = getnewestquestions(limit=100)
    flash('has questions %s'%len(model.QuestionModel()))
    return render_template('question/index.html', qs=qs)

@question.route('/a' , methods=['POST'])
def answer():
    _id = request.form.get('_id', None)
    answer = request.form.get('answer', None)
    if not _id or not answer:
        return redirect(url_for('question.index'))
    uid = session.get('_id', None)
    if not uid:
        return redirect(url_for('user.login', next=url_for('question.detail', qid=_id)))
    result = model.setanswer(_id, {'answer':answer, 'uid':uid})
    if not result:
        return '2'
        return redirect(url_for('question.detail', qid=_id, errorcode=2))
    return redirect(url_for('question.detail', qid=_id))
    
        
        
